package com.sky.business.sys.handler.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.CameraConfig;
import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.event.CameraStatusReportEvent;
import com.sky.business.sys.event.DeviceInfo;
import com.sky.business.sys.handler.MqttEventHandler;
import com.sky.business.sys.service.CameraConfigService;
import com.sky.business.sys.service.SystemConfigService;
import com.sky.business.sys.util.MQTTClientUtils;
import com.sky.common.config.CacheConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.SimpleTimeZone;


/**
 * 设备状态上报事件处理器
 */
@Slf4j
@Component
public class CameraStatusReportEventHandler implements MqttEventHandler {

    public static final ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));

    @Autowired
    private CameraConfigService cameraConfigService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Override
    public boolean match(String topic, String msg,String event) {
        return "CameraStatus".equals(event);
    }

    @Override
    public void handle(String topic, String msg) throws Exception {
        CameraStatusReportEvent cameraStatusReportEvent = objectMapper.readValue(msg, CameraStatusReportEvent.class);
        CameraStatusReportEvent.Metadata metadata = cameraStatusReportEvent.getMetadata();
        CameraConfig cameraConfig = cameraConfigService.findByDeviceId(metadata.getDeviceId());
        SystemConfig systemConfig = systemConfigService.getSystemConfig();
        String reportMsg;
        if(cameraConfig!=null){
            DeviceInfo deviceInfo = DeviceInfo.valueOf(cameraConfig);
            cameraStatusReportEvent.getMetadata().setDeviceInfo(deviceInfo);
            reportMsg = objectMapper.writeValueAsString(cameraStatusReportEvent);
        }else{
            reportMsg = msg;
        }
        MQTTClientUtils.publish(MQTTClientUtils.CMCC_MQTT_CLIENT,  systemConfig.getCmccReportingTopic(), CacheConstants.DEFAULT_QOS, reportMsg);
    }
}
